package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{

    private StringRedisTemplate stringRedisTemplate;

    private String name;
    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.fastUUID().toString(true)+"-";
    private static final RedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
         ((DefaultRedisScript<Long>) UNLOCK_SCRIPT).setLocation(new ClassPathResource("unLock.lua"));
         ((DefaultRedisScript<Long>) UNLOCK_SCRIPT).setResultType(Long.class);

    }

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        String id = ID_PREFIX + Thread.currentThread().getId();

        Boolean isLock = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, id , 1200, TimeUnit.SECONDS);

        return isLock;
    }

    @Override
    public void unlock() {
//        String id =ID_PREFIX + Thread.currentThread().getId();
//
//        if (stringRedisTemplate.opsForValue().get(KEY_PREFIX + name).equals(id) ) {
//        stringRedisTemplate.delete(KEY_PREFIX+name);}
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),
                ID_PREFIX + Thread.currentThread().getId()
        );
    }
}
